<template>
   <div class="login-container">
      <div class="login-bg"></div>
      <div class="login-box">
         <!-- 取消阴影效果 -->
         <el-card
            class="login-box-item"
            shadow="never"
         >
            <h2 class="login-title">登陆你的账户</h2>
            <el-form
               :model="form"
               status-icon
               ref="loginFormRef"
            >
               <el-form-item prop="username">
                  <el-input
                     clearable
                     prefix-icon="User"
                     v-model="form.username"
                     placeholder="账户"
                  ></el-input>
               </el-form-item>
               <el-form-item prop="password">
                  <el-input
                     prefix-icon="Lock"
                     v-model="form.password"
                     @keyup.enter="handleSubmit"
                     type="password"
                     ref="passwordInput"
                     show-password
                     placeholder="密码"
                  ></el-input>
               </el-form-item>

               <el-form-item class="login-item">
                  <!-- 自动登陆复选框 -->
                  <!-- <el-checkbox v-model="form.autoLogin" class="auto-login">自动登陆</el-checkbox> -->
                  <!-- 忘记密码 -->
                  <el-link
                     type="primary"
                     @click="handleForgetPassword"
                     >忘记密码</el-link
                  >
               </el-form-item>

               <el-form-item>
                  <!-- 回车登录 -->
                  <el-button
                     class="login-btn"
                     type="primary"
                     @click="handleSubmit"
                     :loading="loading"
                     >登录</el-button
                  >
               </el-form-item>
            </el-form>
         </el-card>
      </div>
   </div>
</template>

<script setup lang="ts">
   import api from "@/api";
   import { ElMessage } from "element-plus";
   import { ref, nextTick, onMounted, onUnmounted, onActivated } from "vue";
   import { useRouter } from "vue-router";
   import type { FormInstance } from "element-plus";
   import { useRouterStore } from "@/stores/router";
   import { usePublicDataStore } from "@/stores/publicData";

   // 定义类型接口
   interface LoginForm {
      username: string;
      password: string;
      autoLogin?: boolean;
   }

   interface LoginResponse {
      code: number;
      data: {
         admin_token: string;
         admin_info: AdminInfo;
         menu_list?: string[];
      };
      message: string;
   }

   interface AdminInfo {
      id: number;
      username: string;
      avatar?: string;
      [key: string]: any; // 允许其他可能存在的属性
   }

   interface RouteItem {
      path: string;
      title?: string;
      children?: RouteItem[];
      [key: string]: any; // 其他可能的路由属性
   }

   // 状态管理存储
   const publicDataStore = usePublicDataStore();
   const routerStore = useRouterStore();
   const router = useRouter();

   // 表单相关
   const loginFormRef = ref<FormInstance>();
   const form = ref<LoginForm>({
      username: "",
      password: "",
      autoLogin: false,
   });
   const loading = ref<boolean>(false);
   const passwordInput = ref<HTMLInputElement | null>(null);

   // 路由和菜单数据
   const menu_paths: string[] = [];

   // 处理回车键事件
   const handleEnterKey = (event: KeyboardEvent): void => {
      if (event.key === "Enter") {
         if (!form.value.password) {
            nextTick(() => {
               passwordInput.value?.focus(); // 让密码框获得焦点
            });
         } else {
            handleSubmit(); // 如果密码已填写，则尝试提交
         }
      }
   };

   // 添加键盘事件监听器
   const addEnterKeyListener = (): void => {
      window.addEventListener("keydown", handleEnterKey);
   };

   // 移除键盘事件监听器
   const removeEnterKeyListener = (): void => {
      window.removeEventListener("keydown", handleEnterKey);
   };

   // 组件生命周期钩子
   onActivated(() => {
      console.log(111);
      addEnterKeyListener();
   });

   onUnmounted(() => {
      removeEnterKeyListener();
   });

   // 忘记密码处理函数
   const handleForgetPassword = (): void => {
      ElMessage.info("请联系管理员重置密码");
   };

   // 登录提交处理
   const handleSubmit = async (): Promise<void> => {
      if (!form.value.username) {
         ElMessage.error("请输入用户名");
         return;
      } else if (!form.value.password) {
         ElMessage.error("请输入密码");
         return;
      }

      try {
         // loading.value = true;

         //去掉空格
         const res = await api.login.Login({
            username: form.value.username.trim(),
            password: form.value.password.trim(),
         });

         console.log(res, "res");
         if (res.code === 200) {
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("routerIndex", "0");
            localStorage.setItem("userInfo", JSON.stringify(res.data));
            // localStorage.setItem("userInfo", JSON.stringify(res.data.admin_info));
            // 将密码存入本地存储
            localStorage.setItem("password", form.value.password);
            removeEnterKeyListener(); // 登录成功后移除 Enter 键监听

            try {
               let _r = await routerStore.filterMenuList();
               console.log(_r[0].children, "router");
               if (_r[0].children && _r[0].children.length > 0) {
                  router.push(_r[0].children[0].path);
               } else {
                  router.push(_r[0].path);
               }
               // return;
               // router.push("platformManagement/home");.
            } catch (error) {
               console.log(error, "error");
            }
         }
      } catch (error) {
         console.log(error, "error");
      } finally {
         loading.value = false;
      }
   };

   // 过滤路由函数
   const filterRoutes = (routes: RouteItem[]): RouteItem[] => {
      if (!Array.isArray(routes)) return [];

      return routes.reduce<RouteItem[]>((acc, item) => {
         // 检查当前 path 是否匹配 menu_list 中的任一前缀
         const isMatched = menu_paths.some((path) => item.path === path);

         // 如果有 children，则递归处理
         let filteredChildren: RouteItem[] = [];
         if (item.children && Array.isArray(item.children)) {
            filteredChildren = filterRoutes(item.children);
         }

         // 只要当前项匹配 或者 子项中有匹配的，就保留该节点
         if (isMatched || filteredChildren.length > 0) {
            acc.push({
               ...item,
               children: filteredChildren,
            });
            acc = acc.map((entry) => {
               if (!entry.children || entry.children.length === 0) {
                  const { children, ...rest } = entry;
                  return rest;
               }
               return entry;
            });
         }
         return acc;
      }, []);
   };
</script>

<style scoped>
   /* 输入框样式 */
   ::v-deep .el-input__wrapper {
      background-color: rgba(250, 252, 251, 1);
      padding-left: 10px;
   }

   /* 覆盖浏览器自动填充样式 */
   ::v-deep input:-webkit-autofill,
   ::v-deep input:-webkit-autofill:hover,
   ::v-deep input:-webkit-autofill:focus,
   ::v-deep input:-webkit-autofill:active {
      -webkit-box-shadow: 0 0 0 30px rgba(250, 252, 251, 1) inset !important;
      -webkit-text-fill-color: #000 !important;
      transition: background-color 5000s ease-in-out 0s;
   }

   /* 覆盖Element Plus的表单项样式 */
   :deep(.login-item.el-form-item) {
      width: 100% !important;
      margin-bottom: 0 !important;
   }

   :deep(.login-item .el-form-item__content) {
      display: flex !important;
      justify-content: space-between !important;
      width: 100% !important;
   }

   .login-container {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100vh;
   }

   .login-bg {
      width: 50%;
      height: 100%;
      background-image: url("@/assets/denglu.png");
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
   }

   .login-box {
      width: 50%;
      height: 100%;
      background-color: #f6fbff;
      display: flex;
      justify-content: center;
      align-items: center;
   }

   .login-box-item {
      width: 300px;
      padding: 30px;
      background-color: #fff;
      border-radius: 8px;
   }

   .login-title {
      margin-bottom: 20px;
      font-size: 24px;
      font-weight: 500;
   }

   .login-item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
   }

   .auto-login {
      margin-right: 10px;
      font-size: 12px;
   }

   .login-btn {
      width: 100%;
      background-color: #6860ff;
      margin-top: 10px;
   }

   .logo-container {
      position: absolute;
      top: 30px;
      left: 30px;
      display: flex;
      align-items: center;
   }

   .logo-img {
      width: 40px;
      height: 40px;
      margin-right: 10px;
   }

   .logo-text {
      font-size: 20px;
      font-weight: 500;
      color: #333;
   }
</style>
